<template>
  <div class="search-container">
    <van-sticky>
      <form action="/">
        <van-search
          v-model.trim="searchText"
          show-action
          background="#3296fa"
          placeholder="请输入搜索关键词"
          @search="onSearch"
          @cancel="$router.back()"
          @focus="isShowResults=false"
        />
      </form>
    </van-sticky>

    <!-- 搜索结果 -->
    <SearchResults v-if="isShowResults" :searchText="searchText"/>
    <!-- 搜索历史 -->
    <SearchHistory v-else-if="!searchText" :history="history" @search="onSearch" @historyDel="history=[]"/>
    <!-- 搜索建议 -->
    <SearchSuggestion v-else :searchText="searchText" @clickItem="onSearch"/>
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchSuggestion from './components/SearchSuggestion.vue'
import SearchResults from './components/SearchResults.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  data () {
    return {
      searchText: '',
      isShowResults: false,
      // 记录搜索历史
      history: getItem('HMTT-HISTORY') || []
    }
  },

  watch: {
    history: {
      deep: true, // 深度监听
      handler () {
        setItem('HMTT-HISTORY', this.history)
      }
    }
  },

  created () {

  },

  methods: {
    // 敲回车 或 点击搜索建议
    onSearch (val) {
      if (val === '') return
      // 记录搜索历史
      this.history.unshift(val)
      // es6 新方法 可以实现数组去重
      this.history = [...new Set(this.history)]
      this.searchText = val
      this.isShowResults = true
    }
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResults
  }
}
</script>

<style scoped lang="less">
.search-container{
  .van-search__action{
    color: #fff;
  }
}
</style>
